<template>
  <page-header-wrapper>
    <a-card :bordered="false" size="small">
      <div class="table-page-search-wrapper">
        <a-form layout="inline" size="small">
          <a-row :gutter="48">
            <a-col :md="8" :sm="24">
              <a-form-item label="接口名称">
                <a-input size="small" v-model="queryParam.name" @change="() => $refs.table.refresh(true)" allowClear />
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="接口路径">
                <a-input size="small" v-model="queryParam.url" @change="() => $refs.table.refresh(true)" allowClear />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="48">
            <a-col :md="8" :sm="24">
              <a-form-item label="模块">
                <a-select
                  size="small"
                  v-model:value="queryParam.moduleId"
                  :options="moduleList"
                  @change="() => $refs.table.refresh(true)"
                  :filter-option="filterModuleOption"
                  show-search
                  allowClear
                />
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="响应类型">
                <a-radio-group
                  size="small"
                  :key="queryParam.responseType"
                  v-model="queryParam.responseType"
                  @change="() => $refs.table.refresh(true)"
                >
                  <a-radio-button value="">全部</a-radio-button>
                  <a-radio-button value="1">手动模式</a-radio-button>
                  <a-radio-button value="2">Resful模式</a-radio-button>
                </a-radio-group>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :md="8" :sm="24">
              <a-form-item label="描述">
                <a-input size="small" v-model="queryParam.description" placeholder="" allowClear />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="48">
            <a-col :md="(!advanced && 8) || 24" :sm="24">
              <span class="table-page-search-submitButtons" :style="(advanced && { overflow: 'hidden' }) || {}">
                <a-button size="small" type="primary" @click="$refs.table.refresh(true)">查询</a-button>
                <a-button
                  size="small"
                  style="margin-left: 8px"
                  @click="() => ((this.queryParam = { responseType: '' }), $refs.table.refresh(true))"
                >
                  重置
                </a-button>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>

      <div class="table-operator">
        <a-button type="primary" size="small" icon="plus" @click="openEditReponse(null)">新建</a-button>
      </div>

      <s-table ref="table" size="small" rowKey="id" :columns="columns" :data="loadData" showPagination="auto">
        <span slot="serial" slot-scope="text, record, index">
          {{ index + 1 }}
        </span>
        <span slot="module" slot-scope="text, record">
          <a @click="goModule(record.module)">{{ record.module.name }}</a>
        </span>
        <span slot="status" slot-scope="text">
          <a-badge :status="text | statusTypeFilter" :text="text | statusFilter" />
        </span>
        <span slot="description" slot-scope="text">
          <ellipsis :length="20" tooltip>{{ text }}</ellipsis>
        </span>

        <span slot="action" slot-scope="text, record">
          <template>
            <a @click="reponseList(record)">响应列表</a>
            <a-divider type="vertical" />
            <a @click="showMockLog(record)">日志</a>
            <a-divider type="vertical" />
            <a @click="handleDelete(record)">删除</a>
          </template>
        </span>

        <!-- 编辑响应体 -->
        <span slot="editResponse" slot-scope="text, record">
          <template>
            <a @click="openEditReponse(record)">{{ record.name }}</a>
          </template>
        </span>
      </s-table>

      <create-api
        ref="createApi"
        :visible="createApiVisible"
        :form="mdl"
        @handle-ok="handleOk"
        @handle-cancel="handleCancel"
      />

      <a-drawer
        title="响应列表"
        :width="1024"
        :visible="showResponseVisible"
        :body-style="{ paddingBottom: '40px' }"
        :footer-style="{ textAlign: 'right' }"
        @close="reponseList({})"
      >
        <response-list :urlId="mdl.id" />
      </a-drawer>
    </a-card>
  </page-header-wrapper>
</template>

<script>
import { failmsg, okmsg } from '@/api/api'
import { deleteUrl, getList } from '@/api/mock-url'
import { Ellipsis, STable } from '@/components'
import moment from 'moment'

import { getList as getModuleList } from '@/api/mock-module'
import { CreateApi, ResponseList } from './modules'

const statusMap = {
  0: {
    status: 'default',
    text: '关闭',
  },
  1: {
    status: 'processing',
    text: '运行中',
  },
  2: {
    status: 'success',
    text: '已上线',
  },
  3: {
    status: 'error',
    text: '异常',
  },
}

export default {
  name: 'UrlList',
  components: {
    STable,
    Ellipsis,
    CreateApi,
    ResponseList,
  },
  mounted() {
    getModuleList({
      pageNo: 1,
      pageSize: Number.MAX_VALUE,
    }).then((res) => {
      this.moduleList = res.records.map((item) => {
        return {
          key: item.id + item.name,
          label: item.name,
          value: item.id,
        }
      })
      console.log(this.moduleList)
    })
  },
  data() {
    this.columns = [
      {
        title: '#',
        width: '60px',
        scopedSlots: { customRender: 'serial' },
      },
      {
        title: '名称',
        dataIndex: 'name',
        scopedSlots: { customRender: 'editResponse' },
      },
      {
        title: '模块',
        dataIndex: 'moduleId',
        scopedSlots: { customRender: 'module' },
      },
      {
        title: '路径',
        dataIndex: 'url',
      },
      {
        title: '响应类型',
        dataIndex: 'responseType',
        customRender: (val, record) => {
          return (
            <a-switch
              checked={val === 1}
              checked-children="手动模式"
              un-checked-children="Restful模式"
              onChange={this.handleReponseChange}
            />
          )
        },
      },
      {
        title: '描述',
        dataIndex: 'description',
        scopedSlots: { customRender: 'description' },
      },
      {
        title: '操作',
        dataIndex: 'action',
        // fixed: 'right',
        scopedSlots: { customRender: 'action' },
      },
    ]

    return {
      // create model
      createApiVisible: false,
      showResponseVisible: false,
      confirmLoading: false,
      moduleList: [],
      mdl: {},
      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      queryParam: {
        moduleId: this.$route.query.moduleId,
        responseType: '',
      },
      // 加载数据方法 必须为 Promise 对象
      loadData: (parameter) => {
        const requestParameters = Object.assign({}, parameter, this.queryParam)
        return getList(requestParameters)
          .then((res) => {
            return res
          })
          .catch((error) => {
            failmsg(error)
          })
      },
    }
  },
  filters: {
    statusFilter(type) {
      return statusMap[type].text
    },
    statusTypeFilter(type) {
      return statusMap[type].status
    },
  },
  created() {
  },
  computed: {},
  methods: {
    openEditReponse(record) {
      this.createApiVisible = true
      if (record) {
        this.mdl = { ...record, isEdit: true, responseType: String(record.responseType) }
      } else {
        this.mdl = { isEdit: false, responseType: '1' }
      }
    },
    reponseList(record) {
      this.showResponseVisible = null != record.id
      this.mdl = { ...record }
    },
    reponseEdit(record) {
      this.$router.push({ path: '/mock/url-response-list?urlId=' + record.id })
    },
    handleOk() {
      this.createApiVisible = false
      this.$refs.table.refresh(true)
    },
    handleCancel() {
      this.createApiVisible = false
      this.$refs.table.refresh(true)
    },
    handleDelete(record) {
      console.log('record', record)
      deleteUrl(record)
        .then((res) => {
          okmsg(res)
          this.$refs.table.refresh(true)
        })
        .catch((error) => {
          failmsg(error)
        })
    },
    goModule(module) {
      this.$router.push({ path: '/mock/api-module?id=' + module.id })
    },
    filterModuleOption(input, option) {
      return option.data.key.toLowerCase().includes(input.toLowerCase())
    },
    toggleAdvanced() {
      this.advanced = !this.advanced
    },
    resetSearchForm() {
      this.queryParam = {
        date: moment(new Date()),
      }
    },
    handleReponseChange(checked, event) {
      console.log('handleReponseChange', checked, event)
    },
    showMockLog(record) {
      this.$router.push({ path: '/mock/url-log?urlId=' + record.id })
    },
  },
}
</script>
